package com.lam.common.utils.file;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.lam.common.config.AppBaseConfig;
import com.lam.common.constant.CommonConstant;
import com.lam.common.exception.BaseException;
import com.lam.common.exception.ParameterErrorException;
import com.lam.common.model.Qiniu;
import com.lam.common.utils.NumberUtil;
import com.lam.common.utils.SpringUtils;
import com.lam.common.utils.StringUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import cn.hutool.core.util.StrUtil;

/**
 * 文件上传工具
 * @author lamyz
 */
public class FileUploadUtil {
	
	 private static final Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);

    public static Integer getUploadType() {
        Integer uploadType = AppBaseConfig.me().getUploadType();
        if (Objects.isNull(uploadType)) {
            throw new ParameterErrorException("请配置上传文件的存储方式");
        }
        return uploadType;
    }
    
    public static boolean isUploadQiniu() {
    	return NumberUtil.eq(FileUploadUtil.getUploadType(), CommonConstant.UPLOAD_TYPE_QINIU);
    }

    public static String getUploadLocalDir() {
        String attachmentDir = AppBaseConfig.me().getLocalAttachment().getAttachmentDir();
        if (StrUtil.isBlank(attachmentDir)) {
            throw new ParameterErrorException("请配置上传到本地的文件存储目录");
        }
        return attachmentDir;
    }

    public static String getResourceUrl() {
    	if(isUploadQiniu()) {
    		return AppBaseConfig.me().getQiniu().getResourcesUrl();
    	}
    	
        return AppBaseConfig.me().getLocalAttachment().getResourcesUrl();
    }
    
    public static boolean uploadFile(MultipartFile multipartFile, String fileName) {
    	if (isUploadQiniu()) {
    		return upload2Qiniu(multipartFile, fileName);
    	}
    	return upload2Local(multipartFile, fileName);
    }

    public static boolean upload2Local(MultipartFile multipartFile, String fileName) {
        String filePath = getUploadLocalDir();
        File file = new File(filePath + fileName);
        if (!file.exists()) {
            boolean result = file.mkdirs();
            if (!result) {
                throw new BaseException("创建目录：" + filePath + "失败");
            }
        }
        try {
        	multipartFile.transferTo(file);
        	return true;
        } catch (IOException e) {
        	logger.error("文件上传时创建文件异常", e);
            throw new BaseException("文件上传失败！", e);
        }
    }

    public static void deleteLocal(String fileName) {
    	String filePath = getUploadLocalDir();
        File file = new File(filePath + fileName);
        file.deleteOnExit();
    }
    
    public static void deleteFile(String fileName) {
    	if(isUploadQiniu()) {
    		deleteQiniu(fileName);
    	}
    	deleteLocal(fileName);
    }
    
    
    public static boolean upload2Qiniu(MultipartFile multipartFile, String fileName) {
    	
    	if(StringUtils.isBlank(fileName)) {
    		logger.error("上传文件到七牛云的文件名为空");
    		return false;
    	}
    	
        try {
			UploadManager uploadManager = SpringUtils.getBean(UploadManager.class);
			Auth auth = SpringUtils.getBean(Auth.class);
			Qiniu qiniu = AppBaseConfig.me().getQiniu();
			
				// 七牛云文件上传
			String upToken = auth.uploadToken(qiniu.getBucket(), fileName);
			Response response = uploadManager.put(multipartFile.getBytes(), fileName, upToken);
			logger.info("上传文件到七牛云成功, res:{}", response.bodyString());
//			JsonUtil.toJavaObject(response.bodyString(),  DefaultPutRet.class);
			return true;
		} catch (IOException e) {
			logger.error("上传文件到七牛云失败", e);
			throw new BaseException("文件上传失败！");
		} 
    }
    
    public static boolean deleteQiniu(String fileName) {
    	if(StringUtils.isBlank(fileName)) {
    		logger.error("删除七牛云的文件名为空");
    		return false;
    	}
    	
    	try {
			BucketManager bucketManager = SpringUtils.getBean(BucketManager.class);
			Qiniu qiniu = AppBaseConfig.me().getQiniu();
			Response response = bucketManager.delete(qiniu.getBucket(), fileName);
			logger.info("删除七牛云文件成功, res:{}", response.bodyString());
		} catch (QiniuException e) {
			logger.error("删除七牛云文件失败", e);
		}
    	return false;
    }
}
